package com.xjt.sentinel;

import com.alibaba.csp.sentinel.slots.block.RuleConstant;
import com.alibaba.csp.sentinel.slots.block.degrade.DegradeRule;
import com.alibaba.csp.sentinel.slots.block.degrade.DegradeRuleManager;
import com.alibaba.csp.sentinel.slots.block.flow.FlowRule;
import com.alibaba.csp.sentinel.slots.block.flow.FlowRuleManager;
import org.springframework.boot.SpringApplication;
import org.springframework.boot.autoconfigure.SpringBootApplication;

import javax.annotation.PostConstruct;
import java.util.ArrayList;
import java.util.List;

@SpringBootApplication
public class SentinelApplication
{

	public static void main(String[] args)
	{
		SpringApplication.run(SentinelApplication.class, args);
	}


	@PostConstruct
	public void initRules()
	{
		List<FlowRule> rules = new ArrayList<>();
		FlowRule flowRule = new FlowRule();
		flowRule.setResource("user");
		flowRule.setGrade(RuleConstant.FLOW_GRADE_QPS);
		flowRule.setCount(1);
		rules.add(flowRule);
		flowRule = new FlowRule("getFlow");
		flowRule.setGrade(RuleConstant.FLOW_GRADE_QPS);
		flowRule.setCount(2);
		rules.add(flowRule);
		FlowRuleManager.loadRules(rules);
//		添加服务降级配置规则
		List<DegradeRule> degradeRules = new ArrayList<>();
//		创建一个配置对象
		DegradeRule degradeRule = new DegradeRule();
//		设置配置分类，当前设置慢调用类型
//		degradeRule.setGrade(RuleConstant.DEGRADE_GRADE_RT);
//		degradeRule.setResource("testDemotion");
//		设置异常阈值
		degradeRule.setGrade(RuleConstant.DEGRADE_GRADE_EXCEPTION_COUNT);
		//慢调用比例模式下为慢调用临界 RT（超出该值计为慢调用）
		degradeRule.setCount(2);
		//熔断时长，单位为 s
		degradeRule.setTimeWindow(10);
		//设置触发熔断降级得最小请求数
		degradeRule.setMinRequestAmount(2);
		//添加加载
		degradeRules.add(degradeRule);
		degradeRule.setGrade(RuleConstant.DEGRADE_GRADE_RT);
		degradeRule.setResource("testDemotionRt");
		degradeRule.setStatIntervalMs(60*1000);
		degradeRules.add(degradeRule);
		DegradeRuleManager.loadRules(degradeRules);
	}

}
